package webapp.mvc.controllers;

import com.alibaba.fastjson.JSONObject;
import com.zoowii.formutils.BindingResult;
import com.zoowii.formutils.Validator;
import com.zoowii.jpa_utils.extension.Paginator;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.RedirectView;
import webapp.mvc.components.HttpManager;
import webapp.mvc.controllers.forms.RegisterForm;
import webapp.mvc.controllers.forms.SimpleResponse;
import webapp.mvc.exceptions.RedirectException;
import webapp.mvc.exceptions.UserException;
import webapp.mvc.models.UserEntity;
import webapp.mvc.models.WechatPushContentEntity;
import webapp.mvc.models.WechatPushHistoryEntity;
import webapp.mvc.services.IUserService;
import webapp.mvc.utils.NumberUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger LOG = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private HttpManager httpManager;
    @Autowired
    private Validator validator;

    @RequestMapping("/info/{userId}")
    public
    @ResponseBody
    Object userInfo(HttpServletRequest request, HttpServletResponse response, @PathVariable String userId) {
        try {
            httpManager.autoLoginOfWechat(request);
        } catch (RedirectException e) {
            return new RedirectView(e.getUrl());
        }
        UserEntity userEntity = userService.findById(userId);
        if (userEntity == null) {
            return SimpleResponse.fail("找不到用户" + userId).toJSON();
        }
        return SimpleResponse.ok(userEntity).toJSON();
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public
    @ResponseBody
    String createUser(RegisterForm registerForm) {
        BindingResult bindingResult = validator.validate(registerForm);
        if (bindingResult.hasErrors()) {
            return SimpleResponse.fail(bindingResult.getErrors().next().getErrorMessage()).toJSON();
        }
        try {
            UserEntity userEntity = userService.registerUser(registerForm);
            return SimpleResponse.ok(userEntity).toJSON();
        } catch (UserException e) {
            LOG.error("create user error", e);
            return SimpleResponse.fail(e.getMessage()).toJSON();
        }
    }

    @RequestMapping(value = "/change_password", method = RequestMethod.POST)
    public
    @ResponseBody
    String changePassword(HttpServletRequest request) {
        UserEntity userEntity;
        try {
            userEntity = httpManager.currentUser(request);
        } catch (UserException e) {
            return SimpleResponse.fail(e.getMessage()).toJSON();
        }
        try {
            userEntity = userService.changePassword(userEntity.getId(), request.getParameter("password"));
            return SimpleResponse.ok(userEntity).toJSON();
        } catch (UserException e) {
            LOG.error("change password error", e);
            return SimpleResponse.fail(e.getMessage()).toJSON();
        }
    }

    @RequestMapping("/list")
    public
    @ResponseBody
    String listUsers(HttpServletRequest request) {
        Paginator paginator = new Paginator();
        paginator.setPage(NumberUtils.tryParseInt(request.getParameter("page"), 1));
        paginator.setPageSize(NumberUtils.tryParseInt(request.getParameter("page_size"), 10));
        paginator.setPageSize(10);
        paginator.getOrders().add(Pair.of("createTime", false));
        List<UserEntity> userEntities = userService.getUsers(paginator);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records", userEntities);
        jsonObject.put("total", paginator.getTotal());
        return SimpleResponse.ok(jsonObject).toJSON();
    }

    @RequestMapping("/list_wechat_push_contents")
    public
    @ResponseBody
    String listWechatPushContents(HttpServletRequest request) {
        Paginator paginator = new Paginator();
        paginator.setPage(NumberUtils.tryParseInt(request.getParameter("page"), 1));
        paginator.setPageSize(NumberUtils.tryParseInt(request.getParameter("page_size"), 10));
        paginator.setPageSize(10);
        paginator.getOrders().add(Pair.of("createTime", false));
        List<WechatPushContentEntity> wechatPushHistories = userService.getWechatPushContents(paginator);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("records", wechatPushHistories);
        jsonObject.put("total", paginator.getTotal());
        return SimpleResponse.ok(jsonObject).toJSON();
    }

    @RequestMapping("/list_wechat_push_histories/{contentId}")
    public
    @ResponseBody
    String listWechatPushHistories(HttpServletRequest request, @PathVariable String contentId) {
        List<WechatPushHistoryEntity> wechatPushHistoryEntities = userService.getWechatPushHistories(contentId);
        return SimpleResponse.ok(wechatPushHistoryEntities).toJSON();
    }

    @RequestMapping(value = "/delete_wechat_push_content/{contentId}", method = RequestMethod.POST)
    public
    @ResponseBody
    String deleteWechatPushContent(@PathVariable String contentId) {
        userService.deleteWechatPushContent(contentId);
        return SimpleResponse.ok(true).toJSON();
    }
}
